package so.shanku.essential.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import net.tsz.afinal.json.JsonMap;
import net.tsz.afinal.json.JsonParseHelper;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import so.shanku.essential.R;
import so.shanku.essential.activity.ProductCategoryRelationActivity;
import so.shanku.essential.adapter.BrandSearchAdapter;
import so.shanku.essential.adapter.SimpleBrandGridAdater;
import so.shanku.essential.getdata.*;
import so.shanku.essential.utils.Constant;
import so.shanku.essential.utils.ExtraKeys;
import so.shanku.essential.utils.searchUtils.CharacterParser;
import so.shanku.essential.utils.searchUtils.PinyinComparator;
import so.shanku.essential.utils.searchUtils.SideBar;
import so.shanku.essential.utils.searchUtils.SortModel;

import java.util.*;

/**
 * Created by Jaelyn on 2015/9/7.
 * 品牌列表
 */
public class BrandAllFragment extends BaseFragment {
    @ViewInject(R.id.cus_sv)
    private ScrollView cus_sv;
    @ViewInject(R.id.hot_brand_gv)
    private GridView hot_brand_gv;
    /**
     * 顶部布局
     */
    @ViewInject(R.id.hot_goods_layout)
    private LinearLayout headView;

    @ViewInject(R.id.xlv)
    private ListView xlv;
    private BrandSearchAdapter brandListAdapter;
    //private List<JsonMap<String, Object>> dataList;
    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;

    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;
    private ArrayList<SortModel> sourceDataList = new ArrayList<SortModel>();

    /**
     * 热门品牌
     */
    private ArrayList<JsonMap<String,Object>> hotBrandList=new ArrayList<JsonMap<String, Object>>();
    /**
     * 品牌搜索引擎
     */
    @ViewInject(R.id.brand_select_new_sidrbar)
    private SideBar sideBar;

    /**
     * 弹出的字母
     */
    @ViewInject(R.id.brand_select_new_dialog)
    private TextView dialog;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_list_brand, container, false);
        ViewUtils.inject(this, view);
       // headView.setVisibility(View.GONE);
//        headView=inflater.inflate(R.layout.hot_brand_layout,null);
//        ViewUtils.inject(this,headView);
        // 实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();

        pinyinComparator = new PinyinComparator();
        getData_BrandList();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (sourceDataList != null && brandListAdapter != null) {
            brandListAdapter.setList(sourceDataList);
            brandListAdapter.notifyDataSetChanged();
        }
    }

    private void getData_BrandList() {
        loadingToast.show();
        Map<String, Object> params = new HashMap<String, Object>();
        GetDataQueue queue = new GetDataQueue();
        queue.setActionName(GetDataConfing.GetAction_SelectBrandList);
        queue.setCallBack(callBack);
        queue.setParamsNoJson(params);
        queue.setWhat(GetDataConfing.What_SelectBrandList);
        getDataUtil.getData(queue);
    }

    private IGetServicesDataCallBack callBack = new IGetServicesDataCallBack() {

        @Override
        public void onLoaded(GetDataQueue entity) {
            if (entity.isOk()) {
                if (ShowGetDataError.isCodeSuccess(activity, entity.getInfo())) {
                    if (entity.getWhat() == GetDataConfing.What_SelectBrandList) {
                        JsonMap jsonMap = JsonParseHelper.getJsonMap_JsonMap(entity.getInfo(), JsonKeys.Key_Info);
                        hotBrandList= (ArrayList<JsonMap<String, Object>>) jsonMap.getList_JsonMap("hotBrands");

                        sourceDataList = filledData(jsonMap.getList_JsonMap("brandList"));
                        initViews();
                        validateData();
                    } /*else if (entity.getWhat() == GetDataConfing.WHAT_GET_FOCUS_ON) {
                        List<JsonMap<String, Object>> data = JsonParseHelper.getJsonMap_List_JsonMap(
								entity.getInfo(), JsonKeys.Key_Info);
						try {
							boolean isFocus=data.get(0).getBoolean("IsFocus", false);
							if (isFocus) {
								tv_if_attentioned.setSelected(true);
								tv_if_attentioned.setText(R.string.attentioned);
								MyApplication.getInstance().addAttendBrands(vendorId);
							} else {
								tv_if_attentioned.setSelected(false);
								tv_if_attentioned.setText(R.string.attention);
								MyApplication.getInstance().removeAttendBrands(vendorId);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}*/

                }
            } else {
                ShowGetDataError.showNetError(getActivity());
            }
            loadingToast.dismiss();
        }
    };

    private void validateData() {
//		if(sourceDataList==null||sourceDataList.isEmpty()){
//			nodataLayout.setVisibility(View.VISIBLE);
//			xlv.setVisibility(View.GONE);
//		} else {
//			nodataLayout.setVisibility(View.GONE);
//			xlv.setVisibility(View.VISIBLE);
//		}
    }


    /**
     * 为ListView填充数据
     *
     * @param date
     * @return
     */
    private ArrayList<SortModel> filledData(List<JsonMap<String, Object>> date) {
        ArrayList<SortModel> mSortList = new ArrayList<SortModel>();
        for (int i = 0; i < date.size(); i++) {
            SortModel sortModel = new SortModel();
            sortModel.setId(date.get(i).getStringNoNull("brandId"));
            sortModel.setName(date.get(i).getStringNoNull("brandName"));
            sortModel.setIv_log_url(date.get(i).getStringNoNull("brandLogo"));
            sortModel.setTv_msg(date.get(i).getStringNoNull("brandDescri"));
            sortModel.setFocus(date.get(i).getBoolean("IsFocus", false));
            //汉字转换成拼音
            String pinyin = characterParser.getSelling(date.get(i).getStringNoNull("brandName"));
            try {
                String sortString = pinyin.substring(0, 1).toUpperCase();

                // 正则表达式，判断首字母是否是英文字母
                if (sortString.matches("[A-Z]")) {
                    sortModel.setSortLetters(sortString.toUpperCase());
                } else {
                    sortModel.setSortLetters("#");
                }
                mSortList.add(sortModel);
            } catch (StringIndexOutOfBoundsException e) {
                e.printStackTrace();
            }


        }
        return mSortList;

    }

    private void initViews() {
        initHotViews();

        sideBar.setTextView(dialog);

        // 根据a-z进行排序源数据
        Collections.sort(sourceDataList, pinyinComparator);
        brandListAdapter = new BrandSearchAdapter(activity, sourceDataList, null);
        xlv.setAdapter(brandListAdapter);

        //设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = brandListAdapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    xlv.setSelection(position);
                }

            }
        });

        xlv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                //这里要利用adapter.getItem(position)来获取当前position所对应的对象
                String categoryId = sourceDataList.get(position).getId();

                Intent intent = new Intent(activity, ProductCategoryRelationActivity.class);
                intent.putExtra(ExtraKeys.Key_Msg1,2);
                intent.putExtra(Constant.ID, categoryId);
                intent.putExtra(Constant.NAME, sourceDataList.get(position).getName());

                activity.jumpTo(intent);
            }
        });

       cus_sv.scrollTo(0,0);
    }

    /**
     * 热门品牌界面
     */
    private void initHotViews() {
        if(hotBrandList.isEmpty()) {
            headView.setVisibility(View.GONE);
        } else {
            hot_brand_gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String categoryId = hotBrandList.get(position).getStringNoNull("brandId");

                    Intent intent = new Intent(activity, ProductCategoryRelationActivity.class);
                    intent.putExtra(ExtraKeys.Key_Msg1,2);
                    intent.putExtra(Constant.ID, categoryId);
                    intent.putExtra(Constant.NAME, hotBrandList.get(position).getStringNoNull("brandName"));

                    activity.jumpTo(intent);
                }
            });
            SimpleBrandGridAdater hotBrandAdapter = new SimpleBrandGridAdater(activity, hotBrandList);
            hot_brand_gv.setAdapter(hotBrandAdapter);
            // xlv.addHeaderView(headView);
            headView.setVisibility(View.VISIBLE);
        }
        //HotBrandAdapter hotBrandAdapter=new HotBrandAdapter();
    }


//    private String vendorId;
//    private TextView tv_if_attentioned;
//    private BrandSearchAdapter.ItemAttentionChange callback2 = new BrandSearchAdapter.ItemAttentionChange() {
//        @Override
//        public void onStatusChange(int position, TextView tv_if_attention) {
//			tv_if_attentioned = tv_if_attention;
//			vendorId = sourceDataList.get(position).getId();
//			if (Utils.isHasLogin(getActivity())) {
//				activity.getDate_GetFocusOn(callBack, vendorId, getActivity());
//			} else {
//				activity.gotoLogin();
//			}
//        }
//    };

//    @Override
//    public void onHiddenChanged(boolean hidden) {
//        super.onHiddenChanged(hidden);
//        try {
//            brandListAdapter.setList(sourceDataList);
//            brandListAdapter.notifyDataSetChanged();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//    }
}
